package net.oktaeder.office.utils.generators;

import java.util.Calendar;
import java.util.Hashtable;
import java.util.Random;

import net.oktaeder.office.model.Employee;
import net.oktaeder.office.model.Time;
import net.oktaeder.office.simulation.Simulation;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Class to generate new instances of employees
 * 
 * @author tuukka
 *
 */
public class EmployeeGenerator {

	private static Log log = LogFactory.getLog(EmployeeGenerator.class);
	private static EmployeeGenerator instance;
	
	private NameGenerator nameGenerator;
	
	/**
	 * Default constructor
	 *
	 */
	private EmployeeGenerator() {
		nameGenerator = new NameGenerator();
	}
	
	/**
	 * Get instance of employee generator.
	 * 
	 * @return Fully configured EmployeeGenerator
	 */
	public static synchronized EmployeeGenerator getInstance() {
		try {
			if (instance == null) {
				instance = new EmployeeGenerator();
			}
			return instance;
		} catch (Exception ex) {
			log.error("failed to get instance of employee generator", ex);
			return null;
		}
	}
	
	/**
	 * Generates employee according to the given parameters
	 * 
	 * @return generated employee
	 */
	public Employee generateEmployee(Hashtable<String, Object> parameters) {		
		log.warn("Calling unimplemented method");
		
		int age = 0;
		int birthYear;
		int birthMonth;
		int birthDay;
		Random random;
		Time currentTime;
		Employee employee;
		Calendar calendar;
		
		try {
			random = new Random();
			calendar = Calendar.getInstance();
			currentTime = Simulation.getInstance().getTime();
			employee = new Employee();
			
			if (parameters.containsKey("age")) {
				age = (Integer)parameters.get("age");
			}
			
			if (age != 0) {
				birthYear = currentTime.getYear() - age;
			} else {
				log.warn("unimplemented special case");
				birthYear = 1980;
			}
			
			birthMonth = random.nextInt(12) + 1;
			//TODO: small hack, fix later
			birthDay = random.nextInt(25) + 1;
			
			calendar.set(birthYear, birthMonth, birthDay);
			
			employee.setBirthDate(calendar.getTime());
			employee.setPIN(PINGenerator.getInstance().getPIN(calendar.getTime()));
			
			//TODO: temporary value, fix later
			employee.setSalary(random.nextInt(2000) + 2000);
			
			if (parameters.containsKey("name")) {
				employee.setName((String)parameters.get("name"));
			} else {
				employee.setName(nameGenerator.generateSimpleName());				
			}
			
			return employee;
		} catch (Exception ex) {
			log.error("Failed to generate employee", ex);
			return null;
		}
	}
}